﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using Dokan;
using System.IO;

namespace CueMounter.DokanStructure {
	public class DokanMounter {
		private DokanMountOptions currentOptions = null;
		private Thread MountThread;

		public DokanMounter() {
		}

		private void MountThreadProc() {
			DokanOptions dokanOptions = new DokanOptions();
			dokanOptions.DriveLetter = currentOptions.DriveLetter;
			dokanOptions.ThreadCount = 1;
			dokanOptions.VolumeLabel = "Cue Mounter";

			var directoryOperations = new DokanDirectoryOperations(currentOptions.RootDirectories);
			//directoryOperations = new DokanOperationsDebugProxy(directoryOperations);
			DokanNet.DokanMain(dokanOptions, directoryOperations);
		}

		public bool IsMounted {
			get {
				return MountThread != null;
			}
		}

		public void Mount(DokanMountOptions options) {
			if(MountThread != null) {
				Unmount();
			}
			currentOptions = options;
			MountThread = new Thread(MountThreadProc);
			MountThread.Start();
		}

		public DokanMountOptions CurrentOptions {
			get {
				return currentOptions;
			}
		}

		public void Unmount() {
			if(MountThread == null) {
				throw new InvalidOperationException("Can't unmount something that's not mounted");
			}

			DokanNet.DokanUnmount(currentOptions.DriveLetter);
			while(true) {
				if(MountThread.Join(50)) {
					MountThread = null;
					break;
				}
				DokanNet.DokanUnmount(currentOptions.DriveLetter);
			}

			currentOptions = null;
		}
	}
}
